"""
NGINX log_fmt转nginx正则表达式
"""
import re


class NginxParser:
    """
    log_fmt = '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    log_fmt = $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer"
    "$http_user_agent" "$http_x_forwarded_for"
    """
    def __init__(self, log_fmt):
        self.re_rule = self.generator_rule(log_fmt)

    def generator_rule(self, log_fmt):
        fmt = ''.join([item.strip(' ').strip("';") for item in log_fmt.split('\n')])
        specials = re.findall(r'\[.*?\]', fmt)  # []
        for special in specials:
            fmt = fmt.replace(special, f'\\{special}\\')

        words = re.findall(r'\$(\w+)', log_fmt)
        for word in words:
            fmt = re.sub(f'\${word}', f'(?P<{word}>.*?)', fmt, count=1)
        return fmt

    def parser(self, log):
        return re.match(self.re_rule, log).groupdict()


if __name__ == '__main__':
    test_str = '''100.100.0.114 - - [09/Jan/2025:10:43:04 +0800] "GET /assets/el-tree-ffd66896.css HTTP/1.1" 200 4775 "https://192.168.101.79/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" "10.212.134.2"'''
    nginx_parser = NginxParser("""'$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';""")
    a = nginx_parser.parser(test_str)
    print(a)
